package com.itHaipeng.service.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 连接的工具类，用于从数据源中获取一个链接并且和一个线程进行绑定绑定
 */
@Service(value = "connectionUtil")
public class ConnectionUtil {
    //先new一个TheadLocal对象
    private final ThreadLocal<Connection> connectionThreadLocal=new ThreadLocal<>();
    @Autowired
    private DataSource dataSource;
    /**
     * 提供一个获取当前线程的链接
     *
     * @return
     */
   public Connection getThreadConnection(){
       try {
           Connection connection = connectionThreadLocal.get();
           if(connection==null){
               connection= dataSource.getConnection();
               connectionThreadLocal.set(connection);
           }
           return connection;
       }catch (SQLException e){
           throw  new RuntimeException(e);
       }
   }

    /**
     * 把连接和线程解绑
     */
   public void unbindingConnection(){
       connectionThreadLocal.remove();
   }
}
